import { _decorator } from 'cc'
import { ENTITY_STATE_ENUM, EVENT_ENUM } from '../../Enum'

import EventManager from '../../Runtime/EventManager'
import { EnemyManager } from '../../Base/EnemyManager'
import { IEntity } from '../../Levels'
import DataManager from '../../Runtime/DataManager'
import { WoodenSkeletonStateMachine } from './WoodenSkeletonStateMachine'

const { ccclass, property } = _decorator

/**
 * Predefined variables
 * Name = WoodenSkeletonStateManager
 * DateTime = Thu Jul 07 2022 17:30:34 GMT+0800 (中国标准时间)
 * Author = Zero_Y
 * FileBasename = WoodenSkeletonStateManager.ts
 * FileBasenameNoExtension = WoodenSkeletonStateManager
 * URL = db://assets/Scripts/Player/WoodenSkeletonStateManager.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 *
 */

@ccclass('WoodenSkeletonStateManager')
export class WoodenSkeletonStateManager extends EnemyManager {
  async init(params: IEntity) {
    this.fsm = this.addComponent(WoodenSkeletonStateMachine)
    await this.fsm.init()
    super.init(params)
    // 攻击检测，角色出现在NPC附近，NPC主动发起攻击
    EventManager.Instance.on(EVENT_ENUM.PLAYER_MOVE_END, this.onAttack, this)
  }

  // 解绑事件
  onDestroy() {
    super.onDestroy()
    EventManager.Instance.off(EVENT_ENUM.PLAYER_MOVE_END, this.onAttack)
  }
  // NPC攻击角色检测
  onAttack() {
    if (this.state === ENTITY_STATE_ENUM.DEATH || !DataManager.Instance.player) {
      // 已死亡
      return
    }

    const { x: playerX, y: playerY, state: playState } = DataManager.Instance.player
    // 判断角色是否在NPC的上下左右四个格子中
    const disX = Math.abs(this.x - playerX)
    const disY = Math.abs(this.y - playerY)
    // 当前X坐标相等，且Y坐标相距小于等于1格，或者Y坐标相等，X坐标小于等于1格，且判断当前角色不是死亡状态，不然会出现鞭尸现象
    if (
      ((this.x === playerX && disY <= 1) || (this.y === playerY && disX <= 1)) &&
      playState !== ENTITY_STATE_ENUM.DEATH &&
      playState !== ENTITY_STATE_ENUM.AIRDEATH
    ) {
      this.state = ENTITY_STATE_ENUM.ATTACK
      // 通知角色，在地面死亡
      EventManager.Instance.emit(EVENT_ENUM.ATTACK_PLAYER, ENTITY_STATE_ENUM.DEATH)
    } else {
      this.state = ENTITY_STATE_ENUM.IDLE
    }
  }
}
